# -*- coding:utf-8 -*- #

from cmdthread import CmdThread
from threading import RLock

#引入上层目录模块方法
import sys
sys.path.append("..")

from logger.logger import getlogger
from conf import configure

class ProcessManager(object):
    """create def"""
    def __init__(self):
        self.using_queue = {}
        self.recycle_queue = {}

    def create_thread(self):
        thread = None
        try:
            #第一次执行报错,self.using_queue.keys()没有线程id号
            for k in self.using_queue.keys():
                if not self.using_queue[k].is_alive():
                    self.recycle_queue[k] = self.using_queue.pop(k)
            k, thread = self.recycle_queue.popitem()
            self.using_queue[id(thread)] = thread
        except KeyError:
            #
            thread  = CmdThread()
            #setDaemon(bool) 子线程是否随主线程一起结束，必须在start()之前调用，默认为False
            #True 子线程随主线程一起结束
            #False 子线程不随主线程一起结
            thread.setDaemon(True)
            self.using_queue[id(thread)] = thread

        # self.using_queue.keys() 保存线程id号
        # self.using_queue[id(thread)] 是CmdThread()的实例对象
        for k in self.using_queue.keys():
            if self.using_queue[k].is_terminal:
                # 删除并返回键为"k"的条目
                self.using_queue.pop(k)

        #return <CmdThread(Thread-1, initial daemon)>
        return thread

    def thread_num(self):
        return len(self.using_queue) + len(self.recycle_queue)

    def alive_num(self):
        return len(self.using_queue)


    def is_alive(self, thread):
        if id(thread) in self.using_queue:
            return True
        return False

    def recycle_all(self):
        for k in self.using_queue.keys():
            self.recycle(self.using_queue[k])

    def recycle(self, thread):

        try:
            thread.recycle()
            self.recycle_queue[id(thread)] = self.using_queue.pop(id(thread))
        except AttributeError:
            getlogger(configure.logger_path).error('thread %s does not exit' % thread)
        except KeyError:
            getlogger(configure.logger_path).error('thread %s does not exit' % thread)
        except:
            print 'recycle'
            pass


    def terminal_all(self):

        for tid in self.using_queue.keys():
            self.using_queue[tid].terminal()
            self.using_queue.pop(tid)

        for tid in self.recycle_queue.keys():
            self.recycle_queue[tid].terminal()
            self.using_queue.pop(tid)

